// 评论回复数据库
const { DataTypes } = require("sequelize");
const sequelize = require("../config/sequelize");
const User = require("./user");
const Post = require("./post");

const Comment = sequelize.define(
  "Comment",
  {
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: "评论内容",
    },
    parentCommentId: {
      type: DataTypes.INTEGER,
      defaultValue: null,
      comment: "父级评论",
    },
    replyCommentId: {
      type: DataTypes.INTEGER,
      defaultValue: null,
      comment: "回复对象的评论id",
    },
    flag: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      comment: "评论是作者还是其他",
    },
    replyerId: {
      type: DataTypes.INTEGER,
      defaultValue: null,
      allowNull: true,
      references: {
        // 这是对另一个模型的参考
        model: User,

        // 这是引用模型的列名
        key: "id",
      },
    },
    replyerName: {
      type: DataTypes.STRING,
      defaultValue: null,
      comment: "回复用户的昵称",
    },
  },
  {
    sequelize: sequelize,
    tableName: "comment",
    underscored: true,
  }
);
Comment.belongsTo(User, {
  //评论属于微博
  constraints: false,
  foreignKey: "userId",
  as: "user",
});

Comment.belongsTo(Post, {
  //评论属于文章
  constraints: false,
  foreignKey: "postId",
  as: "post",
});

Comment.afterCreate(async (comment) => {
  // 文章评论数+1
  await Post.increment({ commentNum: 1 }, { where: { id: comment.postId } });
});
Comment.afterDestroy(async (comment) => {
  // 文章评论数-1
  await Post.increment({ commentNum: -1 }, { where: { id: comment.postId } });
});

module.exports = Comment;
